<template>
<el-card>
    <div style="width: 100%; text-align: left;">
      <el-button>开始时间：</el-button>
      <el-date-picker
          v-model="searchModel.begin_time"
          type="datetime"
          style="width: 200px"
          placeholder="开始时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYYMMDDHHmmss"
      />
      <el-button style="margin-left: 10px">结束时间：</el-button>
<!--      <el-time-picker
          v-model="searchModel.end_time"
          placeholder="开始时间"
          style="width: 120px"
          format="HH:MM"
          value-format="HH:MM"
      />-->
      <el-date-picker
          v-model="searchModel.end_time"
          type="datetime"
          style="width: 200px"
          placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYYMMDDHHmmss"
      />
      <el-button style="margin-left: 10px">摄像头名称：</el-button>
      <el-input v-model="searchModel.cameraName" placeholder="请输入摄像头名称" clearable style="width: 200px;"></el-input>

      <el-button type="primary" plain @click="checkData" style="margin-left: 10px;">查询</el-button>
    </div>

  <div style="text-align: left; margin-top:10px;">
    <el-button type="danger" plain @click="delPatchExceptionInfo">批量删除</el-button>
    <el-button style="margin-left: 10px">选择识别类型：</el-button>
    <el-select v-model="searchModel.warn_type" placeholder="识别类型" clearable @clear="changeType" >
      <el-option label="实时" value="实时" @click="changeType"/>
      <el-option label="历史" value="历史" @click="changeType"/>
    </el-select>
    <el-button style="margin-left: 10px">选择工区：</el-button>
    <el-select v-model="searchModel.orgName" placeholder="选择工区" clearable @clear="changeType">
      <el-option
          v-for="item in state.org_name_list"
          :key="item"
          :label="item"
          :value="item"
          @click="changeType"
      />
    </el-select>
    <el-button style="margin-left: 10px">选择警告内容：</el-button>
    <el-select v-model="searchModel.warn_content" placeholder="选择警告内容" clearable @clear="changeType">
      <el-option
          v-for="item in state.warn_content_list"
          :key="item"
          :label="item"
          :value="item"
          @click="changeType"
      />
    </el-select>
  </div>

    <div style="margin-top: 10px;">

      <el-table
          :data="exceptionInfoList"
          border
          stripe
          style="width: 100%;height: 568px;"
          @selection-change="delPacthSelectionChange"
      >
        <el-table-column type="selection" min-width="40" />
        <el-table-column label="#" width="50">
          <template #default="scope">
            {{ (searchModel.currentPage-1)*searchModel.pageSize+scope.$index+1 }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="50" />
        <el-table-column prop="camera_name" label="摄像头名称" min-width="100" />
        <el-table-column prop="org_name" label="工区名称" min-width="100" />
<!--        <el-table-column prop="org_name" label="工区名称" min-width="100" />-->
        <el-table-column prop="warn_time" label="警告时间" min-width="150"/>
        <el-table-column prop="warn_content" label="警告内容" min-width="150"/>
        <el-table-column prop="warn_type" label="识别类型" min-width="150"/>
<!--        <el-table-column prop="warn_type" label="识别类型" min-width="120"/>-->
        <el-table-column fixed="right" label="操作" width="136">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editExceptionInfo(scope.row)">查看</el-button>

            <el-popconfirm
                title="确认删除？"
                @confirm="delExceptionInfo(scope.row)"
                confirm-button-text="确认"
                cancel-button-text="取消"
            >
              <template #reference>
                <el-button type="primary" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>

      </el-table>

      <div class="demo-pagination-block" style="margin-top: 10px;">
        <el-pagination
            v-model:current-page="searchModel.currentPage"
            v-model:page-size="searchModel.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog v-model="state.updateDialogVisible" title="查看报警信息" width="70%" draggable center>
      <el-row>
        <el-col :span="12" style="height: 400px">
          <div style="height: 100%;width: 100%;align-items: center;justify-content: center;display: flex;">
            <img :src="require('../images/'+state.imagesUrl+'.jpg')" width="520">
          </div>
        </el-col>
        <el-col :span="12" style="height: 400px">
            <div style="height: 100%;width: 100%;display: flex;align-items: center;justify-content: center;">
              <div class="video" v-show="isPlay" :id="elId"></div>
              <div v-show="!isPlay" style="color: #08979C;font-size: 25px;">点击查看（提示：有效时间只有5分钟）</div>
            </div>
        </el-col>
      </el-row>

      <div style="text-align: center">
        <el-button @click="state.updateDialogVisible = false">退出</el-button>
        <el-button @click="playCamera(state.playcameraUrl)">播放/重播</el-button>
      </div>

    </el-dialog>

  </el-card>

<!--  <el-drawer v-model="state.updateDialogVisible" :show-close="false">
    <template #header="{ close, titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">查看报警信息</h4>
      <el-button type="danger" @click="close">
        <el-icon class="el-icon&#45;&#45;left"><CircleCloseFilled /></el-icon>
        Close
      </el-button>
    </template>
    <div style="text-align: center">
      <img :src="require('../images/'+state.imagesUrl+'.jpg')" width="520">
    </div>
    <div style="height: 100%;width: 100%;display: flex;align-items: center;justify-content: center;">
      <div class="video" v-show="isPlay" :id="elId"></div>
      <div v-show="!isPlay" style="color: #08979C;font-size: 25px;">暂无视频源</div>
    </div>
  </el-drawer>-->
</template>


<script lang="ts" setup>
//rtsp需要的
import FlvJsPlayer from 'xgplayer-flv.js';//在shim-vue.d.ts，中加上declare module 'xgplayer-flv.js'；因为这个没有ts版本，只有js
import Player from 'xgplayer';
import { guid } from './utils/util';

import {ref, toRefs, reactive, onMounted} from "vue";
import {ExceptionInfoData, ESearchModelData, DelPatchListData} from "@/entityapi/base";
import {
  addExceptionInfoAPI,
  delExceptionInfoAPI,
  getExceptionListAPI, getImagesByid,
  updateExceptionInfoAPI
} from "@/api/exceptionapi";
import {ElMessage} from "element-plus";
import {delCameraInfoAPI} from "@/api/cameraapi";
//定义变量

//rtsp需要的
const isPlay = ref(false)
const player = ref<any>({})
const elId = guid()


const state=reactive({
  exceptionInfoList: [] as ExceptionInfoData[],
  searchModel:{
    currentPage: 1,
    pageSize:10,
    cameraName: '',
    warn_content: '',
    orgName:'',
    begin_time:'',
    end_time:'',
    warn_type:''
  }as ESearchModelData,
  total:0,
/*  addDialogVisible:false,*/
  updateDialogVisible:false,

  exceptionInfo:{
    camera_name:"",
    org_name:"",
    warn_time:"",
    warn_content:"",
    warn_type: ""
  } as ExceptionInfoData,

  exceptionInfoNull:{
    camera_name:"",
    org_name:"",
    warn_time:"",
    warn_content:"",
    warn_type: ""
  } as ExceptionInfoData,
  delPatchListData:{
    delPatchList:[0]
  } as DelPatchListData,
  delPatchList:[0],
  imagesUrl:'',
  playcameraUrl:'',
  playFlag:1,
  org_name_list:[""],
  warn_content_list:[""]

});
const{
  exceptionInfoList,
  searchModel,
  total,
}=toRefs(state)

//change pagesize
const handleSizeChange = (val: number) => {
  state.searchModel.pageSize=val
  getExceptionInfoList()
}
//当前页
const handleCurrentChange = (val: number) => {
  state.searchModel.currentPage=val
  getExceptionInfoList()
}

//初始化方法
onMounted(() => {
  state.total=1
  //先随便初始化一条数据
  const aaa={
    id:1,
    camera_name:"string",
    org_name:"string",
    warn_time:"20230822185412",
    warn_content:"string",
    warn_type:"实时",
  }
  const bbb={
    id:1,
    camera_name:"string",
    org_name:"string",
    warn_time:"20230822185412",
    warn_content:"string",
    warn_type:"实时",
  }
  state.exceptionInfoList.push(aaa)
  state.exceptionInfoList.push(bbb)
  getExceptionInfoList()
});

//识别类型选择
function changeType(){
  getExceptionInfoList()
}

function getExceptionInfoList(){
  getExceptionListAPI(state.searchModel).then((res:any) =>{
    //console.log(res)
    state.exceptionInfoList=res.warningList
    state.org_name_list=res.org_name_list
    state.warn_content_list=res.warn_content_list
    state.total=res.total
  })
}
function editExceptionInfo(val:ExceptionInfoData){
  // console.log(val.id)
  // state.imagesUrl="61@20230827100933@persons"
  // state.updateDialogVisible=true
  getImagesByid(val.id).then((res:any) => {
    if (res.code==200){
      state.updateDialogVisible=true
      console.log(res.data)
      state.imagesUrl=res.data
      //state.imagesUrl="require('../images/61@20230827093221@persons.jpg')"
      state.playcameraUrl=res.url
      //playCamera(res.url)
      if(state.playFlag>1){
        changeVideo('ws://localhost:8866/live?url='+res.url)
      }
    }
  })

}

//check
function checkData(){
  if(state.searchModel.begin_time==null){
    state.searchModel.begin_time=""
  }
  if(state.searchModel.end_time==null){
    state.searchModel.end_time=""
  }
  getExceptionInfoList()
}

//delete
function delExceptionInfo(val:ExceptionInfoData){
  const delPatchList=[]
  delPatchList.push(val.id)
  state.delPatchListData.delPatchList=delPatchList
  delExceptionInfoAPI(state.delPatchListData).then((res:any) => {
    if(res.code==200){
      ElMessage({
        showClose: true,
        message: '删除成功',
        type: 'success',
      })
      getExceptionInfoList()
    }else{
      ElMessage({
        showClose: true,
        message: '删除失败，请重试',
        type: 'error',
      })
    }
  })
}

//批量删除
function delPacthSelectionChange(val:any){
  state.delPatchList=[]
  for(let aa in val){
    // console.log(val[aa].id)
    state.delPatchList.push(val[aa].id)
  }
}
//批量删除
function delPatchExceptionInfo(){
  //console.log(state.delPatchList)
  state.delPatchListData.delPatchList=state.delPatchList
  delExceptionInfoAPI(state.delPatchListData).then((res:any) =>{
    if(res.code==200){
      ElMessage({
        showClose: true,
        message: '删除成功',
        type: 'success',
      })
      getExceptionInfoList()
    }else{
      ElMessage({
        showClose: true,
        message: '删除失败，请重试',
        type: 'error',
      })
    }
  })
}


//rtsp
const playCamera=(videourl:string)=>{
  console.log(videourl)
  if(state.playFlag==1){
    createPlayer('ws://localhost:8866/live?url='+videourl, true, 1)
    state.playFlag++;
  }else{
    changeVideo('ws://localhost:8866/live?url='+videourl)
  }

}


const createPlayer = (url: string, hasCloseBtn: boolean, index: number) => {
  //const elId = guid()
  console.log(url);
  console.log(hasCloseBtn);
  console.log(index);

  if (!url) {
    return;
  }

  // if (player) {
  //     changeVideo(url);
  //     return;
  // }

  isPlay.value = true;
  player.value = new FlvJsPlayer({
    id: elId,
    url: url,
    // fitVideoSize: 'auto',
    fluid: true,
    autoplay: true,
    isLive: true,
    playsinline: false,
    screenShot: true,
    whitelist: [''],
    ignores: ['time'],
    closeVideoClick: true,
    // errorTips: '<span class="app-error">无视频源</span>',
    customConfig: {
      isClickPlayBack: false
    },
    flvOptionalConfig: {
      enableWorker: true,
      enableStashBuffer: true, //启用缓存
      stashInitialSize: 4096, //缓存大小4m
      lazyLoad: false,
      lazyLoadMaxDuration: 40 * 60,
      autoCleanupSourceBuffer: true,
      autoCleanupMaxBackwardDuration: 35 * 60,
      autoCleanupMinBackwardDuration: 30 * 60
    } //flv.js可选配置项 [flv.js配置](https://github.com/bilibili/flv.js/blob/master/docs/api.md#config)
  });

  // 自定义播放器按钮
  // let divStr =
  //   '<i class="btn-hover el-icon-camera button-screen-shot" style="font-size: 23px;margin-right: 10px;pointer-events: auto;"></i>' +
  //   '<i class="btn-hover el-icon-s-tools button-set" style="font-size: 23px;margin-right: 10px;pointer-events: auto;"></i>' +
  //   '<i class="btn-hover el-icon-video-camera-solid button-history" style="font-size: 23px;margin-right: 10px;pointer-events: auto;"></i>';

  let divStr = '<i class="btn-hover el-icon-d-arrow-left button-playback" style="font-size: 23px;pointer-events: auto;"></i>';

  let divClose = '<i @click="closePlayer" class="btn-hover el-icon-close app-close-btn-c"></i>';

  let util = Player.util;
  // let customBtn = util.createDom('div', divStr, {}, 'flex align-center justify-center app-player-button'); //'div', divStr, {}, 'class'
  let customBtn = util.createDom(
      'div',
      divStr,
      { style: 'width: 40px;heigth:40px;position: absolute;right: 155px;top: 7px;' },
      'flex align-center justify-center app-player-button'
  ); //'div', divStr, {}, 'class'
  let closeBtn = util.createDom('div', divClose, {}, 'app-close-btn');
  let xgControls = player.value.root.querySelector('xg-controls');
  let xgError = player.value.root.querySelector('xg-error');
  xgControls.appendChild(customBtn);
  player.value.root.appendChild(closeBtn);

  // let shot = customBtn.querySelector('.button-screen-shot');
  // let set = customBtn.querySelector('.button-set');
  // let history = customBtn.querySelector('.button-history');
  let closeBtnc = closeBtn.querySelector('.app-close-btn-c');
  let playback = customBtn.querySelector('.button-playback');

  player.value.on('play', () => { });
  player.value.on('focus', () => {
    if (hasCloseBtn) {
      closeBtn.style.display = 'block';
    }
  });
  player.value.on('ended', () => { });
  player.value.on('blur', () => {
    closeBtn.style.display = 'none';
  });

  player.value.on('error', () => { });

  if (closeBtnc) {
    closeBtnc.addEventListener('click', () => {
      closePlayer();
    });
  }

  // 点击视频时间，设置selectIndex
  // player.video.addEventListener('click', () => {
  //     $emit('clickPlayer', index);
  // });
}

const changeVideo = (url: string) => {
  //console.log(player.value)
  player.value.src = url;
}

const closePlayer = () => {
  isPlay.value = false;
  if (player.value) {
    player.value.destroy();
  }
}
function beforeDestroy() {
  if (player) {
    player.destroy();
  }
  // clearInterval(this.intvBuffer);
  console.log('销毁了');
}
const playObjDestroy = () => {
  if (player.value) {
    player.value.destroy();
  }
  console.log('销毁了');
}

</script>
